<script lang="tsx">
  import { useAppStore } from '@/store';
  import { openWindow, regexUrl } from '@/utils';
  import { listenerRouteChange } from '@/utils/route-listener';
  import { compile, computed, defineComponent, h, ref, watch } from 'vue';
  import { RouteRecordRaw, useRoute, useRouter } from 'vue-router';
  // import useMenuTree from './useMenuTree';

  export default defineComponent({
    emit: ['collapse'],
    setup() {
      const route = useRoute();
      const defaultSelectedKeys = [route.name]; // 默认选中菜单项key数组（默认当前路由name）
      const defaultSelectedKeysParent = [route.matched[0].name]; // 默认展开的子菜单key数组（默认当前路由的父级路由name）
      const appStore = useAppStore();
      const router = useRouter();
      // const { menuTree } = useMenuTree();
      const menuTree = ref<any>([]);

      // 添加对 appStore.route 的监听
      watch(
        () => appStore.route,
        (newRoute) => {
          menuTree.value = appStore.route;
          const dashboard = menuTree.value.find(
            (i: any) => i.path === 'dashboard'
          );
          if (!dashboard) {
            menuTree.value.unshift({
              title: '工作台',
              icon: 'icon-dashboard',
              name: 'dashboard',
              path: 'dashboard',
              level: 0,
              frontRoute: 'null',
              parentId: '0',
              sortOrder: 0.0,
              children: [
                {
                  title: '工作台',
                  name: 'Workplace',
                  path: 'workplace',
                  level: 1,
                  frontRoute: 'views/dashboard/workplace/index',
                  parentId: '1367038467288072192',
                  sortOrder: 0.0,
                },
              ],
            });
          }
        },
        { deep: true }
      );

      // menuTree.value = routers.data.result;
      const loadPermissions: any = async () => {
        menuTree.value = appStore.route;
        const dashboard = menuTree.value.find(
          (i: any) => i.path === 'dashboard'
        );
        if (!dashboard) {
          menuTree.value.unshift({
            title: '工作台',
            icon: 'icon-dashboard',
            name: 'dashboard',
            path: 'dashboard',
            level: 0,
            frontRoute: 'null',
            parentId: '0',
            sortOrder: 0.0,
            children: [
              {
                title: '工作台',
                name: 'Workplace',
                path: 'workplace',
                level: 1,
                frontRoute: 'views/dashboard/workplace/index',
                parentId: '1367038467288072192',
                sortOrder: 0.0,
              },
            ],
          });
        }
      };
      loadPermissions();

      const collapsed = computed({
        get() {
          if (appStore.device === 'desktop') return appStore.menuCollapse;
          return false;
        },
        set(value: boolean) {
          appStore.updateSettings({ menuCollapse: value });
        },
      });

      const openKeys = ref<any>([]);
      openKeys.value = defaultSelectedKeysParent;

      const selectedKey = ref<any>([]);
      selectedKey.value = defaultSelectedKeys;
      const goto = (item: RouteRecordRaw) => {
        if (regexUrl.test(item.path)) {
          openWindow(item.path);
          // selectedKey.value = [item.name as string];
          return;
        }
        if (item.name) {
          selectedKey.value = [item.name as string];

          router.push({
            name: item.name,
          });
        }
      };

      const findMenuOpenKeys = (name: string) => {
        const result: string[] = [];
        let isFind = false;
        const backtrack = (
          item: RouteRecordRaw,
          keys: string[],
          target: string
        ) => {
          if (item.name === target) {
            isFind = true;
            result.push(...keys, item.name as string);
            return;
          }
          if (item.children?.length) {
            item.children.forEach((el) => {
              backtrack(el, [...keys], target);
            });
          }
        };
        menuTree.value.forEach((el: RouteRecordRaw) => {
          if (isFind) return; // Performance optimization
          backtrack(el, [el.name as string], name);
        });
        return result;
      };
      listenerRouteChange((newRoute) => {
        const { requiresAuth, activeMenu, hideInMenu } = newRoute.meta;
        if (requiresAuth && (!hideInMenu || activeMenu)) {
          const menuOpenKeys = findMenuOpenKeys(
            (activeMenu || newRoute.name) as string
          );

          const keySet = new Set([...menuOpenKeys, ...openKeys.value]);
          openKeys.value = [...keySet];

          selectedKey.value = [
            activeMenu || menuOpenKeys[menuOpenKeys.length - 1],
          ];
        }
      }, true);
      const setCollapse = (val: boolean) => {
        if (appStore.device === 'desktop')
          appStore.updateSettings({ menuCollapse: val });
      };

      const renderSubMenu = () => {
        function travel(_route: RouteRecordRaw[], nodes = []) {
          if (_route) {
            _route.forEach((element: any) => {
              // This is demo, modify nodes as needed
              const icon = element?.icon
                ? () => h(compile(`<${element?.icon}/>`))
                : null;
              const node =
                element?.children && element?.children.length !== 0 ? (
                  <a-sub-menu
                    key={element?.name}
                    v-slots={{
                      icon,
                      title: () => h(compile(element?.title || '')),
                    }}
                  >
                    {travel(element?.children)}
                  </a-sub-menu>
                ) : (
                  <a-menu-item
                    key={element?.name}
                    v-slots={{ icon }}
                    onClick={() => goto(element)}
                  >
                    {element.title || ''}
                  </a-menu-item>
                );
              nodes.push(node as never);
            });
          }
          return nodes;
        }
        return travel(menuTree.value);
      };

      return () => (
        <a-menu
          v-model:collapsed={collapsed.value}
          v-model:open-keys={openKeys.value}
          show-collapse-button={appStore.device !== 'mobile'}
          auto-open={false}
          selected-keys={selectedKey.value}
          default-selected-keys={selectedKey.value}
          default-open-keys={openKeys.value}
          auto-open-selected={true}
          level-indent={34}
          style="height: 100%"
          onCollapse={setCollapse}
        >
          {renderSubMenu()}
        </a-menu>
      );
    },
  });
</script>

<style lang="less" scoped>
  :deep(.arco-menu-inner) {
    .arco-menu-inline-header {
      display: flex;
      align-items: center;
    }

    .arco-icon {
      &:not(.arco-icon-down) {
        font-size: 18px;
      }
    }
  }
</style>
